#!/bin/sh
set -eu

assert_fail() {
    if $1 2>&1; then
        echo "FAIL: command '$1' unexpectedly succeeded" >&2
        exit 1
    fi
}

assert_eq() {
    if [ "$1" != "$2" ]; then
        echo "FAIL: expected: '$2' actual: '$1'" >&2
        exit 1
    fi
}

assert_in() {
    if ! echo "$2" | grep -q "$1"; then
        echo "FAIL: '$1' not found in:" >&2
        echo "$2" >&2
        exit 1
    fi
}

echo "TEST: pkaction"
assert_in "org.freedesktop.policykit.exec" "$(pkaction)"
assert_eq "org.freedesktop.policykit.exec" "$(pkaction -a org.freedesktop.policykit.exec)"
assert_in "active.*auth_admin" "$(pkaction --verbose -a org.freedesktop.policykit.exec)"
assert_fail "pkaction -a unknown.action"

echo "TEST: pkcheck"
if [ $(id -u) = 0 ]; then
    assert_eq "" "$(pkcheck -a org.freedesktop.policykit.exec -p 1)"
    assert_eq "" "$(pkcheck -a org.freedesktop.policykit.exec -p $$)"
else
    assert_fail "pkcheck -a org.freedesktop.policykit.exec -p 1"
    assert_fail "pkcheck -a org.freedesktop.policykit.exec -p $$"
fi
